Page({
  data: {
    code: ''
  },

  onLoad() {
    this.login();
  },

  login() {
    wx.login({
      success: (res) => {
        if (res.code) {
          this.setData({
            code: res.code
          });
          this.loginRequest(res.code);
        } else {
          wx.showToast({
            title: '登录失败！',
            icon: 'none'
          });
        }
      }
    });
  },

  loginRequest(code) {
    wx.request({
      url: 'http://localhost:8080/user/user/login',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        code: code
      },
      success: (res) => {
        if (res.data.code === 1) {
          // 保存token和用户信息
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('userInfo', res.data.data);
          
          // 返回上一页或跳转到首页
          wx.navigateBack({
            delta: 1,
            fail: () => {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  }
}); 